from flask import Flask, request, jsonify
from flask_cors import CORS
import hashlib
from database import DatabaseManager
from llm_service import LLMService

app = Flask(__name__)
CORS(app)

# 初始化数据库和LLM服务
db_manager = DatabaseManager()
llm_service = LLMService()

# 用户注册
@app.route('/api/register', methods=['POST'])
def register():
    data = request.json
    username = data.get('username')
    password = hashlib.md5(data.get('password').encode()).hexdigest()
    name = data.get('name')
    phone = data.get('phone')
    budget = data.get('budget')
    preferred_type = data.get('preferred_type')
    
    success, user_id, message = db_manager.create_user(
        username, password, name, phone, budget, preferred_type
    )
    
    if success:
        return jsonify({'success': True, 'message': message, 'user_id': user_id})
    else:
        return jsonify({'success': False, 'message': message})

# 用户登录
@app.route('/api/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username')
    password = hashlib.md5(data.get('password').encode()).hexdigest()
    
    user = db_manager.get_user_by_credentials(username, password)
    
    if user:
        return jsonify({
            'success': True, 
            'user': user.to_dict()
        })
    else:
        return jsonify({'success': False, 'message': '用户名或密码错误'})

# 管理员登录
@app.route('/api/admin/login', methods=['POST'])
def admin_login():
    data = request.json
    username = data.get('username')
    password = hashlib.md5(data.get('password').encode()).hexdigest()
    
    admin = db_manager.get_admin_by_credentials(username, password)
    
    if admin:
        return jsonify({'success': True, 'admin': admin.to_dict()})
    else:
        return jsonify({'success': False, 'message': '管理员用户名或密码错误'})

# 获取用户积分
@app.route('/api/user/points/<int:user_id>')
def get_user_points(user_id):
    points = db_manager.get_user_points(user_id)
    return jsonify({'success': True, 'points': points})

# 购车咨询
@app.route('/api/consult', methods=['POST'])
def consult():
    data = request.json
    user_id = data.get('user_id')
    budget_range = data.get('budget_range')
    preferred_type = data.get('preferred_type')
    usage_scenario = data.get('usage_scenario')
    fuel_type = data.get('fuel_type')
    brand_preference = data.get('brand_preference')
    
    # 构建咨询内容
    consultation_content = f"""
    购车预算: {budget_range}
    偏好车型: {preferred_type}
    使用场景: {usage_scenario}
    燃料类型: {fuel_type}
    品牌偏好: {brand_preference}
    """
    
    try:
        # 调用LLM服务
        llm_response = llm_service.car_consultation(consultation_content)
        
        # 保存咨询记录
        success, consultation_id, message = db_manager.create_consultation(
            user_id, budget_range, preferred_type, usage_scenario, 
            fuel_type, brand_preference, consultation_content, llm_response
        )
        
        if success:
            return jsonify({
                'success': True, 
                'consultation_id': consultation_id,
                'response': llm_response,
                'points_added': 10
            })
        else:
            return jsonify({'success': False, 'message': message})
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'咨询失败: {str(e)}'})

# 获取用户咨询记录
@app.route('/api/consultations/<int:user_id>')
def get_consultations(user_id):
    consultations = db_manager.get_user_consultations(user_id)
    
    consultations_list = []
    for consult in consultations:
        consultations_list.append({
            'id': consult.id,
            'budget_range': consult.budget_range,
            'preferred_type': consult.preferred_type,
            'usage_scenario': consult.usage_scenario,
            'created_at': consult.created_at,
            'llm_response': consult.llm_response[:100] + '...' if len(consult.llm_response) > 100 else consult.llm_response
        })
    
    return jsonify({'success': True, 'consultations': consultations_list})

# 获取咨询详情
@app.route('/api/consultation/<int:consultation_id>')
def get_consultation_detail(consultation_id):
    consultation = db_manager.get_consultation_by_id(consultation_id)
    
    if consultation:
        return jsonify({
            'success': True,
            'consultation': {
                'budget_range': consultation.budget_range,
                'preferred_type': consultation.preferred_type,
                'usage_scenario': consultation.usage_scenario,
                'fuel_type': consultation.fuel_type,
                'brand_preference': consultation.brand_preference,
                'llm_response': consultation.llm_response,
                'created_at': consultation.created_at
            }
        })
    else:
        return jsonify({'success': False, 'message': '咨询记录不存在'})

# 管理员获取所有咨询记录
@app.route('/api/admin/consultations')
def get_all_consultations():
    consultations = db_manager.get_all_consultations()
    return jsonify({'success': True, 'consultations': consultations})

# 管理员获取用户统计
@app.route('/api/admin/user_stats')
def get_user_stats():
    user_stats = db_manager.get_user_stats()
    return jsonify({'success': True, 'stats': user_stats.to_dict()})

# 获取积分记录
@app.route('/api/point_records/<int:user_id>')
def get_point_records(user_id):
    records = db_manager.get_point_records(user_id)
    records_list = [record.to_dict() for record in records]
    return jsonify({'success': True, 'records': records_list})

# 健康检查端点
@app.route('/api/health')
def health_check():
    return jsonify({'success': True, 'message': '服务正常运行'})

if __name__ == '__main__':
    app.run(debug=True, port=5000, host='0.0.0.0')